package com.gykfbxxh.imovie.view.filmsdetail.view;


import android.content.Context;
import android.graphics.Canvas;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.app.utils.util.AppTools;
import com.gykfbxxh.imovie.config.ConfigKey;
import com.gykfbxxh.imovie.config.StyleConstant;
import com.gykfbxxh.imovie.custom.view.web.CustomWebViewDownLoadListener;

import java.lang.reflect.InvocationTargetException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义加载样式的webview
 * Created by xuxinghai on 2016/7/19.
 */
public class FilmPingWebView extends WebView {

    private OnViewSizeChangedListener mOnViewSizeChangedListener;
    private int mContentHeight;//内容高度
    private boolean isDestory;

    public OnViewSizeChangedListener getmOnViewSizeChangedListener() {
        return mOnViewSizeChangedListener;
    }

    public void setOnViewSizeChangedListener(OnViewSizeChangedListener listener) {
        this.mOnViewSizeChangedListener = listener;
    }



    @Override
    public void loadDataWithBaseURL(String baseUrl, String data,
                                    String mimeType, String encoding, String failUrl) {
        if (isDestory) {
            return;
        }
        if(TextUtils.isEmpty(data)){
            super.loadDataWithBaseURL(baseUrl, "",mimeType, encoding, failUrl);
            return;
        }
        String fontStyle = "* {font-size:" + (20) + "px;line-height:" + (30) + "px;} ";
        String webStyle;
        //日间模式
        String webHeadStyle = StyleConstant.STYLE_ONE + fontStyle + StyleConstant.STYLE_TWO;
        webStyle = StyleConstant.WEB_STYLE_DAY_ONE + webHeadStyle  + StyleConstant.WEB_STYLE_DAY_TWO;

        String body = webStyle + data;
//		body = body.replaceAll("<\\s*a\\s+([^>]*)\\s*>", "");
//		body = body.replace("#p#副标题#e#", "");
        super.loadDataWithBaseURL(baseUrl, body + StyleConstant.FOOT,
                mimeType, encoding, failUrl);
        if (!TextUtils.isEmpty(data)) {
            int size = ConfigKey.textSize;
            changeTextSize(size + 1);
        }
    }


    /**
     * 缩小/缩小字体
     */
    public void changeTextSize(int fontSize) {

        if (fontSize < 0) {
            fontSize = 1;
        }
        if (fontSize > 5) {
            fontSize = 5;
        }
        if (fontSize == 1) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(75);
            else
                getSettings().setTextSize(WebSettings.TextSize.SMALLEST);
        } else if (fontSize == 2) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(100);
            else
                getSettings().setTextSize(WebSettings.TextSize.SMALLER);
        } else if (fontSize == 3) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(110);
            else
                getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        } else if (fontSize == 4) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(120);
            else
                getSettings().setTextSize(WebSettings.TextSize.LARGER);
        } else if (fontSize == 5) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
                getSettings().setTextZoom(140);
            else
                getSettings().setTextSize(WebSettings.TextSize.LARGEST);
        }


    }

    @Override
    protected void onSizeChanged(int w, int h, int ow, int oh) {
        super.onSizeChanged(w, h, ow, oh);
        if (mOnViewSizeChangedListener != null) {
            mOnViewSizeChangedListener.onViewSizeChanged(w, h, ow, oh);
        }
    }

    @Override
    public void loadUrl(String url) {
        if(isDestory){
            return;
        }
        super.loadUrl(url);
    }


    public FilmPingWebView(Context context) {
        super(context);
        init(context);
    }

    public FilmPingWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public FilmPingWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    /**
     * 初始化配置
     * @param context
     */
    private void init(Context context){
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(layoutParams);
        setBackgroundColor(0);
        WebSettings settings = getSettings();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);// 提高渲染级别
        try {
            //这行代码内部有可能空指针
            settings.setJavaScriptEnabled(true);// 设置可以运行JS脚本
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        settings.setSupportZoom(false);// 用于设置webview禁止放大
        settings.setBuiltInZoomControls(false);
        // 暂不支持打开多窗口
        settings.setSupportMultipleWindows(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setDomStorageEnabled(true);
        settings.setStandardFontFamily("sans-serif");
        setWebChromeClient(new WebChromeClient());
        setDownloadListener(new CustomWebViewDownLoadListener(context));
    }


    /**
     * 替换html中的img标签
     *
     * @param content
     * @return
     */
    public String replaceImg(String content) {
        if (TextUtils.isEmpty(content)) {
            return content;
        }
        //用正则表达式匹配 IMG标签
        String regEx = "<img\\s[^>]+>";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(content);

        String s = "";
        String src = "src=\"file:///android_asset/loadpic_detail.png\"";
        //匹配img标签中的src属性的正则表达式
        String regEx_img = "(src|SRC)=(\"|\')(.*?)(\"|\')";
        Pattern imgPtn = Pattern.compile(regEx_img);

        Matcher imgmatcher;
        //<img[^<>]*src=[\'\"]([0-9A-Za-z.\\/]*)[\'\"].(.*?)>");
        //循环匹配到了图片
        while (matcher.find()) {
            //循环替换图片
//			float width = 330;
//			int hight = 260;
            String oldStr = matcher.group();
            //得到匹配出来的图片地址
            imgmatcher = imgPtn.matcher(oldStr);
            String imgSrc = "";
            if (imgmatcher.find()) {
                try {
                    imgSrc = imgmatcher.group(3);//得到匹配到的图片地址
                } catch (ArrayIndexOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
            //如果获取的地址不为空 ，则开始替换
            if (!TextUtils.isEmpty(imgSrc) && !TextUtils.isEmpty(content)) {
                s = "<img class=\"lazy\" " + src + " data-original=\"" + imgSrc + "\" />";
                content = content.replace(matcher.group(), s);
            }
        }
        return content;
    }


    /**
     * 滑动到底部(之中执行一次)
     */
    public void scrollBottom(){

        if(mContentHeight == 0){
            //4.4以下的版本距离计算有误差所以我把
            if(AppTools.getSdkVertion() >= Build.VERSION_CODES.KITKAT){
                mContentHeight = computeVerticalScrollRange();//(int) (getContentHeight()*getScaleY());
            }else{
                mContentHeight = computeVerticalScrollRange() - 1025;
            }
        }

        if (getScrollY() < mContentHeight) {
            //如果不在底端则滑至底部
            scrollTo(0, mContentHeight);
        }

    }

    @Override
    public void destroy() {
        try {
            loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            destroyDrawingCache();
            ViewGroup parent = (ViewGroup) getParent();
            if (parent != null) {
                parent.removeView(this);
            }
            removeAllViews();
            isDestory = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.destroy();
    }

    /**
     * 停止播放
     */
    public void stop(){
        //暂停视频
        onPause();

        try {
            getClass().getMethod("onPause").invoke(this, (Object[]) null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 继续播放
     */
    public void play(){
        //继续播放视频
        try {
            getClass().getMethod("onResume").invoke(this, (Object[]) null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    /**
     * 当webview的大小发生变化时回调此接口
     */
    public interface OnViewSizeChangedListener {
        public void onViewSizeChanged(int w, int h, int ow, int oh);
    }


    /**
     * 返回是否被销毁
     * @return
     */
    public boolean getIsDestory(){
        return isDestory;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
